package main

import (
	"context"
	"fmt"
	"github.com/go-test/k8s-client-go/common"
	"github.com/wI2L/jsondiff"
	apps_v1 "k8s.io/api/apps/v1"
	core_v1 "k8s.io/api/core/v1"
	meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

func main() {
	var (
		clientset *kubernetes.Clientset
		err       error
		dp        *apps_v1.Deployment
	)

	// 初始化k8s客户端
	if clientset, err = common.InitClient(); err != nil {
		goto FAIL
	}
	// 获取default命名空间下指定的deployment
	if dp, err = clientset.AppsV1().Deployments("default").Get(context.TODO(), "busybox", meta_v1.GetOptions{}); err != nil {
		goto FAIL
	} else {
		//data, _ := dp.Marshal()
		// fmt.Println(55555, string(data))
		fmt.Println(444444, dp.ObjectMeta.Annotations)
		fmt.Println(555555, dp.Spec)
		currentDeployment := dp.DeepCopy()
		// 修改容器的环境变量
		container := currentDeployment.Spec.Template.Spec.Containers[0]
		// var env []core_v1.EnvVar
		var env = container.Env
		env1 := core_v1.EnvVar{
			Name:  "password",
			Value: "123456",
		}
		env = append(env, env1)
		container.Env = env
		currentDeployment.Spec.Template.Spec.Containers[0] = container
		diffPatch, _ := jsondiff.Compare(dp, currentDeployment)
		for _, v := range diffPatch {
			fmt.Println(v.Type, v.Path, v.Value)
		}

		/*
			_, err = clientset.AppsV1().Deployments("default").Update(context.TODO(), dp, meta_v1.UpdateOptions{})
			if err != nil {
				fmt.Println(err)
			}
			fmt.Println("更新成功")

		*/

	}

	return

FAIL:
	fmt.Println(err)
	return
}
